package cn.bdqn.demo1.controller;


import cn.bdqn.demo1.pojo.User;
import cn.bdqn.demo1.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 控制层，导入service层
 * 这个类所有的方法返回的数据直接给浏览器
 */
@Controller
public class UserControl {
    @Resource//按照配置（依据名称或者依据类型）给属性注入实例
    private UserService userService;

    //查询全部
    @RequestMapping("/list")//路径
    public String userList(Model model) {
        List<User> users = userService.findAll();
        model.addAttribute("users", users);
        return "index";
    }

    //新增数据
    @RequestMapping("/add")
    public String save(User user) {
        userService.save(user);
        return "redirect:/list";
    }

    @RequestMapping("/useradd")
    public String add() {
        return "add";
    }


    //删除数据
//    @RequestMapping("/delete/{id}")
//    public String delete(@PathVariable Integer id, HttpServletResponse servletResponse) throws IOException {
//       int count =userService.delete(id);
//       if(count==1){
//           servletResponse.sendRedirect("/list");
//       }
//        return "error";
//    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        userService.delete(id);
        return "redirect:/list";
    }


    //根据id查找
    @GetMapping("/updatePage/{id}")
    public String updatePage(Model model, @PathVariable int id) {
        User users = userService.get(id);
        model.addAttribute("users", users);
        return "modifi";
    }

    //更新数据
    @PostMapping("/update")
    public String updateUser(Model model, User user, HttpServletRequest request) {
        String id = request.getParameter("id");
        User userById = userService.get(Integer.parseInt(id));
        userService.update(user);
        System.out.println(user);
        return "redirect:/list";
    }


}
